import React, { Fragment } from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Button } from 'antd';
import styles from './style.less';

/**
 *  只提供单字段动态化
 */



// 默认item布局
const defaultItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};
// 默认无label表单布局
const defaultLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 18, offset: 6 },
  },
};


@Form.create()
export default class PateoDynamicForm extends React.Component<any,any> {

  componentDidMount() {
    this.props.onRef(this);
  }
  state = {
    index: 0, // 自增值
    arrayData: [], // 编辑回显时的数组数据
  };

  //以下方法均通过父组件调用
    //①获取动态表单的数据，返回值为数组或者undefined
  onFormSubmit = () => {
    const { form: { validateFields },fieldName } = this.props;
    let data = undefined;
    validateFields((err, values) => {
      if(err) return;
      data = values[fieldName].filter(item => !!item);
    });
    return data;
  };
    //②清空动态表单数据
  onFormClose = () =>{
    const { form:{ resetFields } } = this.props;
    resetFields();
    this.setState({ index: 0,arrayData:[] });
  };
    //③编辑回显时调用，入参为数组数据
  onFormEdit = (arrayData=[]) => {
    this.setState({ index: arrayData.length -1, arrayData })
  };


  // 组件自带方法
  remove = k => {
    const { form: { getFieldValue, setFieldsValue }} = this.props;
    const keys = getFieldValue('keys');
    if (keys.length === 1) return;
    setFieldsValue({ keys: keys.filter(key => key !== k) })
  };
  add = () => {
    const { form: { getFieldValue, setFieldsValue }} = this.props;
    const { index } = this.state;
    const keys = getFieldValue('keys');
    setFieldsValue({ keys: keys.concat(index+1) });
    this.setState({ index: index+1 });
  };

  render() {
    // labelName标题  fieldName表单key  rules校验规则   max最大动态数量
    const { form: { getFieldDecorator, getFieldValue },labelName,fieldName,rules={}, max = 10 } = this.props;
    const { arrayData } = this.state;
    const initialValue = arrayData.length === 0 ? [0] : Array(arrayData.length).fill(true).map((item,index) =>  index);
    getFieldDecorator('keys', { initialValue });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
        <Form.Item
          {...(index === 0 ? defaultItemLayout : defaultLayoutWithOutLabel)}
          label={index === 0 ? labelName : ''}
          key={k}
        >
          {getFieldDecorator(`${fieldName}[${k}]`, {
            rules: [{ required: true, whitespace: true, message: `请输入${labelName}!`,...rules }],
            initialValue: arrayData[k] ? arrayData[k] : undefined,
          })(
              <Input
                placeholder={`请输入${labelName}`}
                style={{ width: '80%', marginRight: 8 }}
              />,
          )}
          { keys.length > 1 ? (
              <MinusCircleOutlined
                className={styles['dynamic-delete-button']}
                disabled={keys.length === 1}
                onClick={() => this.remove(k)} />
          ) : null}
        </Form.Item>
    ));
    return (
      <Fragment>
        {formItems}
        <Form.Item {...defaultLayoutWithOutLabel}>
          {
            keys.length < max ? (
              <Button type="dashed" onClick={this.add} style={{ width: '80%' }}>
                <PlusOutlined /> {`添加${labelName}`}
              </Button>
            ) : null
          }
        </Form.Item>
      </Fragment>
    );
  }
}